<template>
  <!-- 卡片区域 -->
  <el-card class="box-card">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 输入框 -->
    <el-row :gutter="20">
      <el-col :span="10"
        ><div class="grid-content bg-purple">
          <el-input
            placeholder="请输入内容"
            v-model="userInfoList.query"
            clearable
            @clear="getuserinfo()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getuserinfo"
            ></el-button>
          </el-input>
        </div>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="AdDdialogVisible = true"
          >添加用户</el-button
        >
      </el-col>
    </el-row>

    <!-- 用户表格 -->
    <el-table stripe border :data="userList" style="width: 100%">
      <el-table-column type="index" label="#"></el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column prop="mg_state" label="状态">
        <template slot-scope="scope">
          <!-- {{ slot.row }} -->
          <el-switch
            v-model="scope.row.mg_state"
            @change="userStateChange(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <!-- {{ scope.row }} -->
          <!-- 编辑按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteUser(scope.row.id)"
          ></el-button>
          <!-- 设置按钮分配角色 -->
          <el-tooltip
            effect="dark"
            content="分配角色"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="userInfoList.pagenum"
      :page-sizes="[1, 2, 5, 6]"
      :page-size="userInfoList.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 添加用户弹出对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="AdDdialogVisible"
      width="70%"
      @close="restForm"
    >
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="AddFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AdDdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="EditDialogVisible"
      width="50%"
      @close="EditUserRestRules"
    >
      <el-form
        :model="EditUserForm"
        :rules="EditUserRules"
        ref="EditUserFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input v-model="EditUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="EditUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="EditUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="EditUserForecastVerification"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  userInfo,
  // 用户状态
  // userState,
  // 添加用户
  addUser,
  // 展示用户信息
  // showUserInfo,
  // 编辑用户信息提交
  // EditUser,
  // 删除用户
  DeleteUser,
} from '@/request/api.js'
export default {
  name: 'Users',
  data() {
    // 自定义表单验证
    var checkMobile = (rule, value, callback) => {
      const regexpMobile =
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/
      if (regexpMobile.test(value)) {
        // 合法的手机号
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      userInfoList: {
        // 查询用户名
        query: '',
        // 当前页码
        pagenum: 1,
        // 每页数据
        pagesize: 6,
      },
      // 用户列表
      userList: [],
      total: 0,
      // 弹出对话框
      AdDdialogVisible: false,
      // 修改用户对话框
      EditDialogVisible: false,
      // 添加用户表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 修改用户表单
      EditUserForm: {},
      // 添加用户表单验证规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 修改用户表单规则
      EditUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
    }
  },
  mounted() {
    // 获取用户信息
    this.getuserinfo()
  },
  methods: {
    // 获取用户信息
    async getuserinfo() {
      const { data: res } = await userInfo(this.userInfoList)
      console.log('用户信息：', res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户失败！！！')
      } else {
        this.userList = res.data.users
        // console.log(this.userList)
        this.total = res.data.total
      }
    },
    // 一页几条
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.userInfoList.pagesize = newSize
      this.getuserinfo()
    },
    // 当前页码
    handleCurrentChange(pagenum) {
      // console.log(newPage)
      this.userInfoList.pagenum = pagenum
      this.getuserinfo()
    },
    // 双向用户状态改变
    async userStateChange(userInfo) {
      // console.log(userInfo)
      // console.log(userInfo.id)
      // 把状态存到数据库中
      // 发起修改状态请求
      // const res = await userState({
      //   uId: 502,
      //   type: userInfo.mg_state,
      // })
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
        // console.log(res)
      }
      this.$message.success('更新用户状态成功')
    },
    // 对话框关闭重置对话框
    restForm() {
      this.$refs.AddFormRef.resetFields()
    },
    // 点击确定进行表单预校验和网络请求，添加用户
    addUser() {
      this.$refs.AddFormRef.validate(async (vaildata) => {
        // console.log(vaildata)
        if (!vaildata) {
        } else {
          // 添加用户请求
          const { data: res } = await addUser(this.addUserForm)
          console.log(res)
          this.AdDdialogVisible = false
          this.getuserinfo()
        }
      })
    },
    // 展示修改用户对话框
    async showEditDialog(id) {
      // console.log(id)
      // 根据id查询用户信息
      const { data: res } = await this.$http.get(`users/${id}`)
      console.log('id查询用户信息：', res)
      this.EditUserForm = res.data
      this.EditDialogVisible = true
    },
    // 重置校验规则
    EditUserRestRules() {
      this.$refs.EditUserFormRef.resetFields()
    },
    // 对编辑用户表单进行预检验
    EditUserForecastVerification() {
      this.$refs.EditUserFormRef.validate(async (value) => {
        console.log(value)
        if (!value) {
        } else {
          // 发起修改用户提交的请求
          const { data: res } = await this.$http.put(
            `users/${this.EditUserForm.id}`,
            {
              mobile: this.EditUserForm.mobile,
              email: this.EditUserForm.email,
            }
          )
          if (res.meta.status !== 200) {
            this.$message.error('更新用户信息失败！')
          }
          console.log(res)
          this.EditDialogVisible = false
          // 更新用户信息列表
          this.getuserinfo()
          this.$message.success('更新用户信息成功！')
        }
      })
    },
    // 删除用户
    async deleteUser(id) {
      console.log(id)
      const result = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(result)   结果是字符串 成功是comfirm 失败cancel
      if (result !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // const { data: res } = await this.$http.delete(
      //   `users/${this.EditUserForm.id}`
      // )
      // console.log(res)
      // this.getuserinfo()

      const { data: res } = await DeleteUser(id)
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.getuserinfo()
    },
  },
}
</script>

<style></style>
